package priv.lirenhe.dissertation.component.crawler_robot.url_manager.url_ini;

import java.io.File;
import java.util.Iterator;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;

public class SeedUrlConfig {
	
	private static PropertiesConfiguration propConfig01 = null;
	private static PropertiesConfiguration propConfig02 = null;
	
	public static synchronized void iniPropConfig(){
		propConfig01 = PropConfig.getPropConfig("params.properties");
		if(propConfig01 != null){
			String notUsedSeedUrlPath = null;
			notUsedSeedUrlPath = (String) propConfig01.getProperty("not-used-seedurl-path");
			System.out.println(notUsedSeedUrlPath);
			propConfig02 = PropConfig.getPropConfig(new File(notUsedSeedUrlPath));
		}
	}
	
	/**
	 * 
	 * @return
	 */
	public synchronized static String getOneSeedUrl(){
		String oneSeedUrlValue = null;
		String oneSeedUrlKey = null;
		Iterator<String> keyIterator = null;
		String number = null;
		String flag = null;
		keyIterator = propConfig02.getKeys();
		
		if(!keyIterator.hasNext()){
			return null;
		}
		//得到序号最小的未使用的key
		int loopNum = 1;
		int minNumber = 0;
		while(keyIterator.hasNext()){
			String key = (String) keyIterator.next();
			String[] keyStrs = key.split("-");
			number = keyStrs[0];
			flag = keyStrs[1];
			
			if(flag.equals("Used")){
				continue;
			}else{
				if(loopNum == 1){
					minNumber = new Integer(number);
				}else{
					if(minNumber > new Integer(number)){
						minNumber = new Integer(number);
					}
				}
			}
			loopNum++;
		}
		oneSeedUrlKey = minNumber + "-" + "NotUsed";
		
		System.out.println("降序提出种子url oneSeedUrlKey="+oneSeedUrlKey);
		
		oneSeedUrlValue = (String) propConfig02.getProperty(oneSeedUrlKey);
		
		String oldSeedUrlKey = oneSeedUrlKey;
		String newSeedUrlKey = minNumber + "-" + "Used";
		
		propConfig02.clearProperty(oldSeedUrlKey);
		propConfig02.setProperty(newSeedUrlKey, oneSeedUrlValue);
		try {
			propConfig02.save(propConfig02.getFile());
		} catch (ConfigurationException e) {
			e.printStackTrace();
		}
		
		return oneSeedUrlValue;
	
	}
	
}
